package com.sinodata.bsm.cicp.collector.common;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.AbstractJDBCCollector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.common.constants.SeparatorConstants;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author Administrator
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2013-1-8 下午5:25:26          Administrator        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class SqlReturnObjectCollector extends AbstractJDBCCollector {
    private static Logger logger = Logger.getLogger(SqlReturnObjectCollector.class);

    @Override
    public String[] getPropMeta() {
        return new String[] { "$1" };
    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "DBType", "SQL", "DBName" };
    }

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        String[] propMetas = this.getParamMeta();
        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        ResPropertyValue resPropertyValueX = new ResPropertyValue();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
        String dbtype = this.paramMap.get("DBType");
        String dbname = this.paramMap.get("DBName");
        String sql = this.paramMap.get("SQL");
        System.out.println(sql);
        try {
            ResultSet rs = this.getCachedResultSet(dbtype, ip, dbname, sql);
            int countColumn = rs.getMetaData().getColumnCount();
            StringBuilder sb = new StringBuilder();
            while (rs.next()) {
                for (int i = 1; i <= countColumn; i++) {
                    String currentColumn = rs.getString(i) == null ? "" : rs.getString(i);
                    if (i < countColumn) {
                        sb.append(currentColumn).append(SeparatorConstants.COL_SEPARATOR);
                    } else {
                        sb.append(currentColumn).append(SeparatorConstants.LIN_SEPARATOR);
                    }
                }
            }
            propValues[0] = ResPropertyValue.createPropValue(sb.toString(), propMetas[0]);
            resPropertyValueX.setValues(propValues);
            values.add(resPropertyValueX);
            return values;
        } catch (Exception e) {
            logger.error("SqlReturnObjectCollector product error:ip[" + ip + "],DBType[" + dbtype + "],DBName[" + dbname + "],sql[" + sql + "]", e);
            throw new CollectorException(e);
        }
    }
}
